<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Gateway," />










<meta name="description" content="前言随着公司业务的发展，目前公司的服务数已达到了21个，旧业务一直都是一个业务一个域名，再加上我们有n套测试环境，因此运维要维护的域名为21n个（这个数只多不少），大大增加了运维的维护成本，包括新起一套测试环境域名问题也十分困扰人。 同时微服务之前的鉴权原本也是通过nginx塞请求头的方式来处理，每次新起服务都需要重新配置。 跨域也是在各个服务里自己配置，有时候开发会忘记在各自服务里配置跨域，导致">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringCloud-Gateway接入兼容旧业务踩坑记录">
<meta property="og:url" content="http://yoursite.com/p/50150557.html">
<meta property="og:site_name" content="Molzhao">
<meta property="og:description" content="前言随着公司业务的发展，目前公司的服务数已达到了21个，旧业务一直都是一个业务一个域名，再加上我们有n套测试环境，因此运维要维护的域名为21n个（这个数只多不少），大大增加了运维的维护成本，包括新起一套测试环境域名问题也十分困扰人。 同时微服务之前的鉴权原本也是通过nginx塞请求头的方式来处理，每次新起服务都需要重新配置。 跨域也是在各个服务里自己配置，有时候开发会忘记在各自服务里配置跨域，导致">
<meta property="og:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2022/2022-02-16/Buffer.png">
<meta property="article:published_time" content="2022-01-25T06:09:00.000Z">
<meta property="article:modified_time" content="2022-02-16T10:25:57.015Z">
<meta property="article:author" content="MolZhao">
<meta property="article:tag" content="Gateway">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2022/2022-02-16/Buffer.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"我们没有找到任何搜索结果: ${query}","hits_stats":"找到约${hits}条结果 (用时 ${time}ms)"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/p/50150557.html"/>





  <title>SpringCloud-Gateway接入兼容旧业务踩坑记录 | Molzhao</title>
  








<meta name="generator" content="Hexo 4.2.1"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Molzhao</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/index.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>

                

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/p/50150557.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="MolZhao">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Molzhao">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">SpringCloud-Gateway接入兼容旧业务踩坑记录</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2022-01-25T14:09:00+08:00">
                2022-01-25
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E4%BA%92%E8%81%94%E7%BD%91%E6%9E%B6%E6%9E%84/index.html" itemprop="url" rel="index">
                    <span itemprop="name">互联网架构</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/p/50150557.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/p/50150557.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i> 阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  4.8k 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  23 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>随着公司业务的发展，目前公司的服务数已达到了21个，旧业务一直都是一个业务一个域名，再加上我们有n套测试环境，因此运维要维护的域名为21n个（这个数只多不少），大大增加了运维的维护成本，包括新起一套测试环境域名问题也十分困扰人。</p>
<p>同时微服务之前的鉴权原本也是通过nginx塞请求头的方式来处理，每次新起服务都需要重新配置。</p>
<p>跨域也是在各个服务里自己配置，有时候开发会忘记在各自服务里配置跨域，导致时间成本的增加。</p>
<p>综上所述在服务数日益增加的需求下，接入网关刻不容缓。</p>
<hr>
<h2 id="系统配置及版本"><a href="#系统配置及版本" class="headerlink" title="系统配置及版本"></a>系统配置及版本</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 线上服务器配置</span></span><br><span class="line">双节点8核心CPU 16G内存</span><br></pre></td></tr></table></figure>


<table>
<thead>
<tr>
<th>依赖</th>
<th align="center">版本</th>
</tr>
</thead>
<tbody><tr>
<td>SpringCloud</td>
<td align="center">Hoxton.SR10</td>
</tr>
<tr>
<td>SpringGateway</td>
<td align="center">2.2.7.RELEASE</td>
</tr>
<tr>
<td>SpringBoot</td>
<td align="center">2.3.8.RELEASE</td>
</tr>
<tr>
<td>SA-TOKEN</td>
<td align="center">1.25.0</td>
</tr>
<tr>
<td>***</td>
<td align="center"></td>
</tr>
</tbody></table>
<h2 id="全局过滤器"><a href="#全局过滤器" class="headerlink" title="全局过滤器"></a>全局过滤器</h2><p>全局过滤器不需要配置在每个路由规则下就可以生效可以用来配置网关日志、白名单、鉴权等功能，通过实现Odered接口来实现过滤器优先级,优先级如下</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Useful constant for the highest precedence value.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> java.lang.Integer#MIN_VALUE 0x80000000;</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">int</span> HIGHEST_PRECEDENCE = Integer.MIN_VALUE;</span><br><span class="line"></span><br><span class="line">	<span class="comment">/**</span></span><br><span class="line"><span class="comment">	 * Useful constant for the lowest precedence value.</span></span><br><span class="line"><span class="comment">	 * <span class="doctag">@see</span> java.lang.Integer#MAX_VALUE 0x7fffffff</span></span><br><span class="line"><span class="comment">	 */</span></span><br><span class="line">	<span class="keyword">int</span> LOWEST_PRECEDENCE = Integer.MAX_VALUE;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GlobalLogFilter</span> <span class="keyword">implements</span> <span class="title">GlobalFilter</span>, <span class="title">Ordered</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> GatewaySecurityProperties gatewaySecurityProperties;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Mono&lt;Void&gt; <span class="title">filter</span><span class="params">(ServerWebExchange exchange, GatewayFilterChain chain)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (Boolean.TRUE.equals(gatewaySecurityProperties.getLogEnable())) &#123;</span><br><span class="line">            ServerHttpRequest request = exchange.getRequest();</span><br><span class="line">            log.info(<span class="string">"====================REQUEST INFO START===================="</span>);</span><br><span class="line">            String hostName = Optional.of(exchange).map(ServerWebExchange::getRequest).map(ServerHttpRequest::getRemoteAddress).map(InetSocketAddress::getHostName).orElse(CharSequenceUtil.EMPTY);</span><br><span class="line">            String clientIp = Optional.of(exchange).map(ServerWebExchange::getRequest).map(ServerHttpRequest::getRemoteAddress).map(InetSocketAddress::getAddress).map(InetAddress::getHostAddress).orElse(CharSequenceUtil.EMPTY);</span><br><span class="line">            log.info(<span class="string">"==REMOTE ADDRESS  : [&#123;&#125;]&#123;&#125;"</span>, hostName, clientIp);</span><br><span class="line">            log.info(<span class="string">"==REQUEST URL     : [&#123;&#125;]&#123;&#125;"</span>, request.getMethod(), Optional.of(exchange).map(ServerWebExchange::getRequest).map(HttpRequest::getURI).map(URI::getPath).orElse(CharSequenceUtil.EMPTY));</span><br><span class="line">            log.info(<span class="string">"==REQUEST TOKEN   : [&#123;&#125;]"</span>, Optional.of(exchange)</span><br><span class="line">                    .map(ServerWebExchange::getRequest)</span><br><span class="line">                    .map(HttpMessage::getHeaders)</span><br><span class="line">                    .map(x -&gt; x.get(GlobalConstant.TOKEN_HEADER))</span><br><span class="line">                    .map(y -&gt; y.get(<span class="number">0</span>))</span><br><span class="line">                    .orElse(CharSequenceUtil.EMPTY));</span><br><span class="line"></span><br><span class="line">            log.info(<span class="string">"=====================REQUEST INFO END======================"</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> chain.filter(exchange);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> FilterOrder.GLOBAL_LOG_FILTER_ORDER;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="统一接口权限"><a href="#统一接口权限" class="headerlink" title="统一接口权限"></a>统一接口权限</h2><p>统一接口权限在项目中采用的是SA-TOKEN，因此按照<a href="https://sa-token.dev33.cn/doc/index.html#/micro/gateway-auth" target="_blank" rel="noopener">SA-TOKEN接口权限</a>文档编码即可。可以集成nacos配置中心，变成实时可控的权限。</p>
<p>这边需要注意先注册SA-TOKEN全局过滤器</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SaTokenConfigure</span> </span>&#123;</span><br><span class="line">    <span class="comment">// 注册 Sa-Token全局过滤器</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> SaReactorFilter <span class="title">getSaReactorFilter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> SaReactorFilter();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 全局鉴权开关</span></span><br><span class="line"><span class="keyword">private</span> Boolean urlPermissionsEnable;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 权限映射关系</span></span><br><span class="line"><span class="keyword">private</span> Map&lt;String, List&lt;String&gt;&gt; urlPermissions;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GlobalPermissionFilter</span> <span class="keyword">implements</span> <span class="title">GlobalFilter</span>, <span class="title">Ordered</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Resource</span></span><br><span class="line">    <span class="keyword">private</span> GatewaySecurityProperties gatewaySecurityProperties;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Mono&lt;Void&gt; <span class="title">filter</span><span class="params">(ServerWebExchange exchange, GatewayFilterChain chain)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span> (Boolean.TRUE.equals(gatewaySecurityProperties.getUrlPermissionsEnable())) &#123;</span><br><span class="line">            Map&lt;String, List&lt;String&gt;&gt; urlPermissions = gatewaySecurityProperties.getUrlPermissions();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">            	<span class="comment">// 判断用户是否有该权限</span></span><br><span class="line">                urlPermissions.keySet().forEach(perm -&gt; SaRouter.match(urlPermissions.get(perm), () -&gt; StpUtil.checkPermission(perm)));</span><br><span class="line">            &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> BusinessException(ResultStatus.UNAUTHORIZED);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> chain.filter(exchange);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> FilterOrder.GLOBAL_PERMISSION_FILTER_ORDER;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h2 id="统一APIGateway-knife4j接入"><a href="#统一APIGateway-knife4j接入" class="headerlink" title="统一APIGateway knife4j接入"></a>统一APIGateway knife4j接入</h2><h3 id="网关侧配置"><a href="#网关侧配置" class="headerlink" title="网关侧配置"></a>网关侧配置</h3><p>首先引入knife4j的依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.github.xiaoymin<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>knife4j-spring-boot-starter<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Primary</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SwaggerProvider</span> <span class="keyword">implements</span> <span class="title">SwaggerResourcesProvider</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String API_URI = <span class="string">"/v2/api-docs"</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 网关应用名称</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;spring.application.name&#125;"</span>)</span><br><span class="line">    <span class="keyword">private</span> String self;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> RouteLocator routeLocator;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SwaggerProvider</span><span class="params">(RouteLocator routeLocator)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.routeLocator = routeLocator;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;SwaggerResource&gt; <span class="title">get</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        List&lt;SwaggerResource&gt; resources = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        List&lt;String&gt; routes = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        routeLocator.getRoutes()</span><br><span class="line">                .filter(route -&gt; route.getUri().getHost() != <span class="keyword">null</span> &amp;&amp; Objects.equals(route.getUri().getScheme(), <span class="string">"lb"</span>) &amp;&amp; !self.equalsIgnoreCase(route.getUri().getHost()))</span><br><span class="line">                .subscribe(route -&gt;</span><br><span class="line">                        routes.add(route.getUri().getHost()));</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 记录已经添加过的server，存在同一个应用注册了多个服务在注册中心上</span></span><br><span class="line">        Set&lt;String&gt; processed = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">        routes.forEach(service -&gt; &#123;</span><br><span class="line">            <span class="comment">// 拼接url ，请求swagger的url</span></span><br><span class="line">            String url = <span class="string">"/"</span> + service.toLowerCase() + API_URI;</span><br><span class="line">            <span class="keyword">if</span> (!processed.contains(url)) &#123;</span><br><span class="line">                processed.add(url);</span><br><span class="line">                resources.add(createSwaggerResource(service, url));</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;);</span><br><span class="line">        <span class="keyword">return</span> resources;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> SwaggerResource <span class="title">createSwaggerResource</span><span class="params">(String name, String url)</span> </span>&#123;</span><br><span class="line">        SwaggerResource swaggerResource = <span class="keyword">new</span> SwaggerResource();</span><br><span class="line">        swaggerResource.setName(name);</span><br><span class="line">        swaggerResource.setUrl(url);</span><br><span class="line">        swaggerResource.setLocation(url);</span><br><span class="line">        swaggerResource.setSwaggerVersion(<span class="string">"3.0"</span>);</span><br><span class="line">        <span class="keyword">return</span> swaggerResource;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SwaggerHandler</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span>(required = <span class="keyword">false</span>)</span><br><span class="line">    <span class="keyword">private</span> SecurityConfiguration securityConfiguration;</span><br><span class="line">    <span class="meta">@Autowired</span>(required = <span class="keyword">false</span>)</span><br><span class="line">    <span class="keyword">private</span> UiConfiguration uiConfiguration;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> SwaggerProvider swaggerProvider;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">SwaggerHandler</span><span class="params">(SwaggerProvider swaggerProvider)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.swaggerProvider = swaggerProvider;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/swagger-resources/configuration/security"</span>)</span><br><span class="line">    <span class="keyword">public</span> Mono&lt;ResponseEntity&lt;SecurityConfiguration&gt;&gt; securityConfiguration() &#123;</span><br><span class="line">        <span class="keyword">return</span> Mono.just(<span class="keyword">new</span> ResponseEntity&lt;&gt;(</span><br><span class="line">                Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/swagger-resources/configuration/ui"</span>)</span><br><span class="line">    <span class="keyword">public</span> Mono&lt;ResponseEntity&lt;UiConfiguration&gt;&gt; uiConfiguration() &#123;</span><br><span class="line">        <span class="keyword">return</span> Mono.just(<span class="keyword">new</span> ResponseEntity&lt;&gt;(</span><br><span class="line">                Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@GetMapping</span>(<span class="string">"/swagger-resources"</span>)</span><br><span class="line">    <span class="keyword">public</span> Mono&lt;ResponseEntity&lt;List&lt;SwaggerResource&gt;&gt;&gt; swaggerResources() &#123;</span><br><span class="line">        <span class="keyword">return</span> Mono.just((<span class="keyword">new</span> ResponseEntity&lt;&gt;(swaggerProvider.get(), HttpStatus.OK)));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如此之后，访问<code>http://${网关域名}/doc.html</code>，能看到统一swagger文档，网关会根据服务名去业务服务去自动收集swagger的json展示在页面上，因此子服务也需要集成swagger框架,即访问<code>${业务服务}/v2/api-docs</code>能拿到业务服务的接口json文档即可。</p>
<h3 id="业务服务侧配置"><a href="#业务服务侧配置" class="headerlink" title="业务服务侧配置"></a>业务服务侧配置</h3><figure class="highlight"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;io.springfox&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;springfox-swagger2&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br><span class="line">&lt;dependency&gt;</span><br><span class="line">    &lt;groupId&gt;io.springfox&lt;/groupId&gt;</span><br><span class="line">    &lt;artifactId&gt;springfox-swagger-ui&lt;/artifactId&gt;</span><br><span class="line">&lt;/dependency&gt;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * &lt;p&gt; Description : SwaggerConfiguration &lt;/p&gt;</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@date</span> : 2020/3/31 11:54</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableSwagger</span>2</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">SwaggerConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 创建API应用</span></span><br><span class="line"><span class="comment">     * apiInfo() 增加API相关信息</span></span><br><span class="line"><span class="comment">     * 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现，</span></span><br><span class="line"><span class="comment">     * 本例采用指定扫描的包路径来定义指定要建立API的目录。</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Docket <span class="title">createRestApi</span><span class="params">()</span> </span>&#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">        <span class="comment">//版本类型是swagger2</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Docket(DocumentationType.SWAGGER_2)</span><br><span class="line">                <span class="comment">//通过调用自定义方法apiInfo，获得文档的主要信息</span></span><br><span class="line">                .apiInfo(apiInfo())</span><br><span class="line">                .select()</span><br><span class="line">                .apis(RequestHandlerSelectors.basePackage(<span class="string">"xyz.molzhao.controller"</span>))<span class="comment">//扫描该包下面的API注解</span></span><br><span class="line">                .paths(PathSelectors.any())</span><br><span class="line">                .build().globalOperationParameters(getGlobalParameter());</span><br><span class="line"></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 创建该API的基本信息（这些基本信息会展现在文档页面中）</span></span><br><span class="line"><span class="comment">     * 访问地址：http://项目实际地址/swagger-ui.html</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> ApiInfo <span class="title">apiInfo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ApiInfoBuilder()</span><br><span class="line">                .title(<span class="string">"使用Swagger2 构建RESTful APIS - zy"</span>) <span class="comment">//接口管理文档首页显示</span></span><br><span class="line">                .description(<span class="string">"zy - Swagger使用演示"</span>)<span class="comment">//API的描述</span></span><br><span class="line">                .termsOfServiceUrl(<span class="string">"www.footmark.top"</span>)<span class="comment">//网站url等</span></span><br><span class="line">                .version(<span class="string">"1.0"</span>)</span><br><span class="line">                .build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">	<span class="comment">// 设置全局参数</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> List&lt;Parameter&gt; <span class="title">getGlobalParameter</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        ParameterBuilder ticketPar = <span class="keyword">new</span> ParameterBuilder();</span><br><span class="line">        List&lt;Parameter&gt; pars = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        ticketPar.name(<span class="string">"token"</span>).description(<span class="string">"token"</span>)</span><br><span class="line">                .modelRef(<span class="keyword">new</span> ModelRef(<span class="string">"string"</span>)).parameterType(<span class="string">"query"</span>)</span><br><span class="line">                .required(<span class="keyword">false</span>).build();</span><br><span class="line">        pars.add(ticketPar.build());</span><br><span class="line"></span><br><span class="line">        ParameterBuilder model = <span class="keyword">new</span> ParameterBuilder();</span><br><span class="line">        model.name(<span class="string">"model"</span>).description(<span class="string">"设备"</span>)</span><br><span class="line">                .modelRef(<span class="keyword">new</span> ModelRef(<span class="string">"String"</span>)).parameterType(<span class="string">"query"</span>)</span><br><span class="line">                .required(<span class="keyword">true</span>).build();</span><br><span class="line">        pars.add(model.build());</span><br><span class="line">        <span class="keyword">return</span> pars;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>业务服务集成swaager文档即可，这边可以继续进行优化，将swagger封装成一个starter供给另外的服务引用</p>
<hr>
<h2 id="动态路由"><a href="#动态路由" class="headerlink" title="动态路由"></a>动态路由</h2><p>由于网关是一个比较基础的服务，他的重启几乎会影响所有后端服务的访问，因此不能经常重启，此时我们就非常需要能实时改换路由规则的一个功能。本文将结合nacos实现网关动态路由</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 网关路由仓库配置（本项目采用nacos配置中心）</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">GatewayConfig</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> <span class="keyword">long</span> DEFAULT_TIMEOUT = <span class="number">30000</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String NACOS_SERVER_ADDR;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String NACOS_NAMESPACE;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String NACOS_ROUTE_DATA_ID;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> String NACOS_ROUTE_GROUP;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;spring.cloud.nacos.discovery.server-addr&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNacosServerAddr</span><span class="params">(String nacosServerAddr)</span> </span>&#123;</span><br><span class="line">        NACOS_SERVER_ADDR = nacosServerAddr;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;spring.cloud.nacos.discovery.namespace:#&#123;null&#125;&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNacosNamespace</span><span class="params">(String nacosNamespace)</span> </span>&#123;</span><br><span class="line">        NACOS_NAMESPACE = nacosNamespace;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;nacos.gateway.route.config.data-id&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNacosRouteDataId</span><span class="params">(String nacosRouteDataId)</span> </span>&#123;</span><br><span class="line">        NACOS_ROUTE_DATA_ID = nacosRouteDataId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Value</span>(<span class="string">"$&#123;nacos.gateway.route.config.group&#125;"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setNacosRouteGroup</span><span class="params">(String nacosRouteGroup)</span> </span>&#123;</span><br><span class="line">        NACOS_ROUTE_GROUP = nacosRouteGroup;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>动态路由实现类</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 通过nacos下发动态路由配置,监听Nacos中gateway-route配置</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@DependsOn</span>(&#123;<span class="string">"gatewayConfig"</span>&#125;) <span class="comment">// 依赖于gatewayConfig bean</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicRouteServiceImplByNacos</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> DynamicRouteServiceImpl dynamicRouteService;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">private</span> ConfigService configService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@PostConstruct</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">init</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            configService = initConfigService();</span><br><span class="line">            <span class="keyword">if</span> (configService == <span class="keyword">null</span>) &#123;</span><br><span class="line">                log.warn(<span class="string">"initConfigService fail"</span>);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            String configInfo = configService.getConfig(GatewayConfig.NACOS_ROUTE_DATA_ID, GatewayConfig.NACOS_ROUTE_GROUP, GatewayConfig.DEFAULT_TIMEOUT);</span><br><span class="line">            log.info(<span class="string">"获取网关当前配置:\r\n&#123;&#125;"</span>, configInfo);</span><br><span class="line">            List&lt;RouteDefinition&gt; definitionList = JSON.parseArray(configInfo, RouteDefinition<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">            <span class="keyword">for</span> (RouteDefinition definition : definitionList) &#123;</span><br><span class="line">                log.info(<span class="string">"update route : &#123;&#125;"</span>, definition.toString());</span><br><span class="line">                dynamicRouteService.add(definition);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            log.error(<span class="string">"初始化网关路由时发生错误"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">        dynamicRouteByNacosListener(GatewayConfig.NACOS_ROUTE_DATA_ID, GatewayConfig.NACOS_ROUTE_GROUP);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 监听Nacos下发的动态路由配置</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> dataId</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> group</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">dynamicRouteByNacosListener</span><span class="params">(String dataId, String group)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            configService.addListener(dataId, group, <span class="keyword">new</span> Listener() &#123;</span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">receiveConfigInfo</span><span class="params">(String configInfo)</span> </span>&#123;</span><br><span class="line">                    log.info(<span class="string">"进行网关更新:\n\r&#123;&#125;"</span>, configInfo);</span><br><span class="line">                    List&lt;RouteDefinition&gt; definitionList = JSON.parseArray(configInfo, RouteDefinition<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">                    log.info(<span class="string">"update route : &#123;&#125;"</span>, definitionList.toString());</span><br><span class="line">                    dynamicRouteService.updateList(definitionList);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> Executor <span class="title">getExecutor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                    log.info(<span class="string">"getExecutor\n\r"</span>);</span><br><span class="line">                    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (NacosException e) &#123;</span><br><span class="line">            log.error(<span class="string">"从nacos接收动态路由配置出错!!!"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 初始化网关路由 nacos config</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> ConfigService <span class="title">initConfigService</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Properties properties = <span class="keyword">new</span> Properties();</span><br><span class="line">            properties.setProperty(<span class="string">"serverAddr"</span>, GatewayConfig.NACOS_SERVER_ADDR);</span><br><span class="line">            <span class="keyword">if</span> (CharSequenceUtil.isNotEmpty(GatewayConfig.NACOS_NAMESPACE)) &#123;</span><br><span class="line">                properties.setProperty(<span class="string">"namespace"</span>, GatewayConfig.NACOS_NAMESPACE);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> configService = NacosFactory.createConfigService(properties);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            log.error(<span class="string">"初始化网关路由时发生错误"</span>, e);</span><br><span class="line">            <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 动态更新路由网关service</span></span><br><span class="line"><span class="comment"> * 1）实现一个Spring提供的事件推送接口ApplicationEventPublisherAware</span></span><br><span class="line"><span class="comment"> * 2）提供动态路由的基础方法，可通过获取bean操作该类的方法。该类提供新增路由、更新路由、删除路由，然后实现发布的功能。</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DynamicRouteServiceImpl</span> <span class="keyword">implements</span> <span class="title">ApplicationEventPublisherAware</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RouteDefinitionWriter routeDefinitionWriter;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RouteDefinitionLocator routeDefinitionLocator;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 发布事件</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> ApplicationEventPublisher publisher;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setApplicationEventPublisher</span><span class="params">(ApplicationEventPublisher applicationEventPublisher)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.publisher = applicationEventPublisher;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 删除路由</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> id</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result&lt;Void&gt; <span class="title">delete</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.info(<span class="string">"网关删除路由，路由ID： &#123;&#125;"</span>,id);</span><br><span class="line">            <span class="keyword">this</span>.routeDefinitionWriter.delete(Mono.just(id)).subscribe();</span><br><span class="line">            <span class="keyword">this</span>.publisher.publishEvent(<span class="keyword">new</span> RefreshRoutesEvent(<span class="keyword">this</span>));</span><br><span class="line">            <span class="keyword">return</span> Result.success();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">return</span> Result.failed(GatewayResultEnum.DELETE_ROUTE_FAIL);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新路由</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> definitions</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result&lt;Void&gt; <span class="title">updateList</span><span class="params">(List&lt;RouteDefinition&gt; definitions)</span> </span>&#123;</span><br><span class="line">        log.info(<span class="string">"网关更新路由：&#123;&#125;"</span>,definitions);</span><br><span class="line">        <span class="comment">// 删除缓存routerDefinition</span></span><br><span class="line">        List&lt;RouteDefinition&gt; routeDefinitionsExits =  routeDefinitionLocator.getRouteDefinitions().buffer().blockFirst();</span><br><span class="line">        <span class="keyword">if</span> (!CollectionUtils.isEmpty(routeDefinitionsExits)) &#123;</span><br><span class="line">            routeDefinitionsExits.forEach(routeDefinition -&gt; &#123;</span><br><span class="line">                log.info(<span class="string">"delete routeDefinition:&#123;&#125;"</span>, routeDefinition);</span><br><span class="line">                delete(routeDefinition.getId());</span><br><span class="line">            &#125;);</span><br><span class="line">        &#125;</span><br><span class="line">        definitions.forEach(<span class="keyword">this</span>::updateById);</span><br><span class="line">        <span class="keyword">return</span> Result.success();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 更新路由</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> definition</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span>  Result&lt;Void&gt; <span class="title">updateById</span><span class="params">(RouteDefinition definition)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            log.info(<span class="string">"gateway update route &#123;&#125;"</span>,definition);</span><br><span class="line">            <span class="keyword">this</span>.routeDefinitionWriter.delete(Mono.just(definition.getId()));</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            log.error(<span class="string">"更新失败未找到路由，routeId: &#123;&#125;"</span>, definition.getId());</span><br><span class="line">            <span class="keyword">return</span> Result.failed(GatewayResultEnum.UPDATE_ROUTE_FAIL);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            routeDefinitionWriter.save(Mono.just(definition)).subscribe();</span><br><span class="line">            <span class="keyword">this</span>.publisher.publishEvent(<span class="keyword">new</span> RefreshRoutesEvent(<span class="keyword">this</span>));</span><br><span class="line">            <span class="keyword">return</span> Result.success();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            <span class="keyword">return</span> Result.failed(GatewayResultEnum.UPDATE_ROUTE_FAIL);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 增加路由</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> definition</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Result&lt;Void&gt; <span class="title">add</span><span class="params">(RouteDefinition definition)</span> </span>&#123;</span><br><span class="line">        log.info(<span class="string">"gateway add route &#123;&#125;"</span>,definition);</span><br><span class="line">        routeDefinitionWriter.save(Mono.just(definition)).subscribe();</span><br><span class="line">        <span class="keyword">this</span>.publisher.publishEvent(<span class="keyword">new</span> RefreshRoutesEvent(<span class="keyword">this</span>));</span><br><span class="line">        <span class="keyword">return</span> Result.success();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>由此在nacos中新增配置文件gateway-router即可实现动态路由，可以根据自己需要新增过滤器或者更改路由规则</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">nacos:</span></span><br><span class="line">  <span class="attr">gateway:</span></span><br><span class="line">    <span class="attr">route:</span></span><br><span class="line">      <span class="attr">config:</span></span><br><span class="line">        <span class="attr">data-id:</span> <span class="string">gateway-router</span></span><br><span class="line">        <span class="attr">group:</span> <span class="string">DEFAULT_GROUP</span></span><br></pre></td></tr></table></figure>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">[&#123;</span><br><span class="line">    <span class="attr">"id"</span>: <span class="string">"xyz"</span>,</span><br><span class="line">    <span class="attr">"order"</span>: <span class="number">0</span>,</span><br><span class="line">    <span class="attr">"predicates"</span>: [&#123;</span><br><span class="line">        <span class="attr">"args"</span>: &#123;</span><br><span class="line">            <span class="attr">"pattern"</span>:<span class="string">"/xyz/**"</span></span><br><span class="line">        &#125;,</span><br><span class="line">        <span class="attr">"name"</span>: <span class="string">"Path"</span></span><br><span class="line">    &#125;],</span><br><span class="line">    <span class="attr">"filters"</span>: [&#123;<span class="attr">"name"</span>:<span class="string">"StripPrefix"</span>,<span class="attr">"args"</span>:&#123;<span class="attr">"_genkey_0"</span>:<span class="string">"1"</span>&#125;&#125;],</span><br><span class="line">    <span class="attr">"uri"</span>: <span class="string">"lb://xyz"</span></span><br><span class="line">&#125;]</span><br></pre></td></tr></table></figure>

<p>一般情况下，我们为了方便可能在网关转发的时候直接使用gateway自带的根据服务名进行路由转发，但这不影响动态路由的配置，两者可以共存。</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">gateway:</span></span><br><span class="line">     <span class="attr">discovery:</span></span><br><span class="line">       <span class="attr">locator:</span></span><br><span class="line">         <span class="attr">enabled:</span> <span class="literal">true</span>  <span class="comment">#开启根据微服务名称自动转发</span></span><br><span class="line">         <span class="attr">lower-case-service-id:</span> <span class="literal">true</span></span><br><span class="line">         <span class="attr">filters:</span></span><br><span class="line">         <span class="comment">## 当开启服务名转发配置后想用另外的过滤器，需要先加上StripPrefix</span></span><br><span class="line">             <span class="bullet">-</span> <span class="string">StripPrefix=1</span></span><br><span class="line">             <span class="bullet">-</span> <span class="string">CorsFilterFactory</span></span><br></pre></td></tr></table></figure>
<hr>
<h2 id="跨域及重复跨域问题解决"><a href="#跨域及重复跨域问题解决" class="headerlink" title="跨域及重复跨域问题解决"></a>跨域及重复跨域问题解决</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Access to XMLHttpRequest at <span class="string">'http://192.168.0.144:8762/ctginms_main2019/api/traceRoute/getMapData'</span> from origin <span class="string">'http://localhost:8080'</span> has been blocked by CORS policy: The <span class="string">'Access-Control-Allow-Origin'</span> header contains multiple values <span class="string">'*, *'</span>, but only one is allowed.</span><br></pre></td></tr></table></figure>
<p>由于之前的老项目每个服务对应一个域名，且存在很多h5页面直接根据老域名进行调用，前端修改域名起来十分困难，因此后端需要兼容这些老域名。</p>
<p>之前的技术架构中，每个业务服务都有自己的跨域配置，且都开启了（为了兼容老h5页面访问），现在需要接入统一网关，新服务的跨域配置理当在网关中统一配置，不然后续服务多起来一个配置要重复n次，不太合理，由此造成了当经过网关访问到某个旧服务（自己开启跨域配置）的时候会出现以上错误。意思就是重复跨域了。</p>
<h3 id="什么是跨域"><a href="#什么是跨域" class="headerlink" title="什么是跨域"></a>什么是跨域</h3><p>何谓同源:URL由协议、域名、端口和路径组成，如果两个URL的协议、域名和端口相同，则表示它们同源。浏览器的同源策略，从一个域上加载的脚本不允许访问另外一个域的文档属性 ，是浏览器上为安全性考虑实施的非常重要的安全策略。违反了这个同源策略我们就认为是跨域访问了，浏览器会拒绝这项请求。</p>
<p>以上看起来十分拗口，想要理解上面的内容也有点困难，其实可以简单的理解，后端返回的resonse中跨域的配置比如配置了允许的请求头，当前请求是否带有其他的非法请求头访问，如果是非法的即不能访问。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_ALLOW_CREDENTIALS = <span class="string">"Access-Control-Allow-Credentials"</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_ALLOW_HEADERS = <span class="string">"Access-Control-Allow-Headers"</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_ALLOW_METHODS = <span class="string">"Access-Control-Allow-Methods"</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_ALLOW_ORIGIN = <span class="string">"Access-Control-Allow-Origin"</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_EXPOSE_HEADERS = <span class="string">"Access-Control-Expose-Headers"</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_MAX_AGE = <span class="string">"Access-Control-Max-Age"</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_REQUEST_HEADERS = <span class="string">"Access-Control-Request-Headers"</span>;</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">final</span> String ACCESS_CONTROL_REQUEST_METHOD = <span class="string">"Access-Control-Request-Method"</span>;</span><br></pre></td></tr></table></figure>

<h3 id="重复跨域解决"><a href="#重复跨域解决" class="headerlink" title="重复跨域解决"></a>重复跨域解决</h3><p>之前说过网关和业务服务都开启了跨域配置因此我们可以理解成一个请求链经过网关和业务服务都给他的<code>ResonseHeader</code>加上了以<code>Access-Control-Allow-Origin</code>为Key，<code>*</code>为Value的键值对，这就是重复跨域。</p>
<p>我们可以看下<code>HttpHeaders</code>的数据结构,他实现了名为<code>MultiValueMap</code>的数据结构，而这个底层的数据结构是<code>Map&lt;K, List&lt;V&gt;&gt;</code>因此我们可以知道这个数据结构一个key可以存放多个值，由此之前的<code>*,*</code>也可以理解了</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public class HttpHeaders implements MultiValueMap&lt;String, String&gt;, Serializable &#123;</span><br><span class="line">    private static final long serialVersionUID &#x3D; -8578554704772377436L;</span><br><span class="line">    public static final String ACCEPT &#x3D; &quot;Accept&quot;;</span><br><span class="line">    public static final String ACCEPT_CHARSET &#x3D; &quot;Accept-Charset&quot;;</span><br><span class="line">    public static final String ACCEPT_ENCODING &#x3D; &quot;Accept-Encoding&quot;;</span><br><span class="line">    public static final String ACCEPT_LANGUAGE &#x3D; &quot;Accept-Language&quot;;</span><br><span class="line">    public static final String ACCEPT_RANGES &#x3D; &quot;Accept-Ranges&quot;;</span><br><span class="line">    public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS &#x3D; &quot;Access-Control-Allow-Credentials&quot;;</span><br><span class="line">    ...</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<p>我们只需要在网关侧拦截到请求链的response，对<code>ResonseHeader</code>进行处理即可，如果有重复的value则给他去重在放行给浏览器这样问题也就迎刃而解了。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 处理重复跨域问题, 清除重复的response-header</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Component</span></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CorsFilterFactory</span> <span class="keyword">extends</span> <span class="title">ModifyResponseBodyGatewayFilterFactory</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">final</span> Set&lt;String&gt; corsHeaderSet;</span><br><span class="line"></span><br><span class="line">    &#123;</span><br><span class="line">        corsHeaderSet = <span class="keyword">new</span> HashSet&lt;&gt;();</span><br><span class="line">        corsHeaderSet.add(HttpHeaders.ACCESS_CONTROL_ALLOW_CREDENTIALS);</span><br><span class="line">        corsHeaderSet.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS);</span><br><span class="line">        corsHeaderSet.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS);</span><br><span class="line">        corsHeaderSet.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN);</span><br><span class="line">        corsHeaderSet.add(HttpHeaders.ACCESS_CONTROL_MAX_AGE);</span><br><span class="line">        corsHeaderSet.add(HttpHeaders.VARY);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> GatewayFilter <span class="title">apply</span><span class="params">(Config config)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> ModifyResponseGatewayFilter(<span class="keyword">this</span>.getConfig());</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> Config <span class="title">getConfig</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Config cf = <span class="keyword">new</span> Config();</span><br><span class="line">        cf.setRewriteFunction(byte[].class, byte[].class, getRewriteFunction());</span><br><span class="line">        <span class="keyword">return</span> cf;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 重写 Response 响应头</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;</span></span><br><span class="line"><span class="comment">     * 如果跨域响应头重复则去除</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 重写方法</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">private</span> RewriteFunction&lt;<span class="keyword">byte</span>[], <span class="keyword">byte</span>[]&gt; getRewriteFunction() &#123;</span><br><span class="line">        <span class="keyword">return</span> (exchange, resp) -&gt; &#123;</span><br><span class="line">            HttpHeaders oldHeaders = exchange.getResponse().getHeaders();</span><br><span class="line">            HttpHeaders newHeaders = <span class="keyword">new</span> HttpHeaders();</span><br><span class="line">            oldHeaders.forEach((key, value) -&gt; &#123;</span><br><span class="line">                <span class="keyword">if</span> (judgeCorsHeader(key)) &#123;</span><br><span class="line">                    List&lt;String&gt; responseValue = value.stream().distinct().collect(Collectors.toList());</span><br><span class="line">                    <span class="comment">// 当去重后的集合大小小于去重前的集合大小，说明有重复响应头</span></span><br><span class="line">                    <span class="keyword">if</span> (value.size() &gt; responseValue.size()) &#123;</span><br><span class="line">                        newHeaders.addAll(key, responseValue);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;);</span><br><span class="line"></span><br><span class="line">            newHeaders.forEach((key, value) -&gt; &#123;</span><br><span class="line">                oldHeaders.remove(key);</span><br><span class="line">                oldHeaders.addAll(key, value);</span><br><span class="line">            &#125;);</span><br><span class="line">            <span class="keyword">return</span> Mono.just(resp);</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">judgeCorsHeader</span><span class="params">(String header)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> corsHeaderSet.contains(header);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最后我们只需要在对应的路由规则上配置该路由器即可</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">gateway:</span></span><br><span class="line">     <span class="attr">discovery:</span></span><br><span class="line">       <span class="attr">locator:</span></span><br><span class="line">         <span class="attr">enabled:</span> <span class="literal">true</span>  <span class="comment">#开启根据微服务名称自动转发</span></span><br><span class="line">         <span class="attr">lower-case-service-id:</span> <span class="literal">true</span></span><br><span class="line">         <span class="attr">filters:</span></span><br><span class="line">         <span class="comment">## 当开启服务名转发配置后想用另外的过滤器，需要先加上StripPrefix</span></span><br><span class="line">             <span class="bullet">-</span> <span class="string">StripPrefix=1</span></span><br><span class="line">             <span class="bullet">-</span> <span class="string">CorsFilterFactory</span></span><br></pre></td></tr></table></figure>
<hr>
<h2 id="Exceeded-limit-on-max-bytes-to-buffer-262144"><a href="#Exceeded-limit-on-max-bytes-to-buffer-262144" class="headerlink" title="Exceeded limit on max bytes to buffer : 262144"></a>Exceeded limit on max bytes to buffer : 262144</h2><p>接入完统一网关之后，上线的第一天晚上，监听到网关侧有大量<code>Exceeded limit on max bytes to buffer : 262144</code>该类型错误。经过排查发现是因为业务服务返回的json串大于了256k导致的。</p>
<h3 id="配置文件配置缓冲区大小"><a href="#配置文件配置缓冲区大小" class="headerlink" title="配置文件配置缓冲区大小"></a>配置文件配置缓冲区大小</h3><p>经过参考网上的解决方案之后,按照如下配置即可放大缓冲区的大小，但是在SpringBoot版本<code>2.3.8.RELEASE</code>中配置并没有起作用。</p>
<figure class="highlight yaml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">spring:</span></span><br><span class="line">  <span class="attr">codec:</span></span><br><span class="line">    <span class="attr">max-in-memory-size:</span> <span class="string">2MB</span></span><br></pre></td></tr></table></figure>


<h3 id="配置类配置缓冲区大小"><a href="#配置类配置缓冲区大小" class="headerlink" title="配置类配置缓冲区大小"></a>配置类配置缓冲区大小</h3><p>于是采用了通过配置来进行配置缓冲区大小，但是在当前SpringBoot版本中这种方法也没有起到作用。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableWebFlux</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WebFluxWebConfig</span> <span class="keyword">implements</span> <span class="title">WebFluxConfigurer</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">configureHttpMessageCodecs</span><span class="params">(ServerCodecConfigurer configurer)</span> </span>&#123;</span><br><span class="line">        configurer.defaultCodecs().maxInMemorySize(<span class="number">2</span> * <span class="number">1024</span> * <span class="number">1024</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="重写Spring原文件"><a href="#重写Spring原文件" class="headerlink" title="重写Spring原文件"></a>重写Spring原文件</h3><p>我们可以看到在SpringBoot<code>2.3.8.RELEASE</code>中这个缓存区大小被硬编码了，因此我们如何更改都无效，这边采用了一个不怎么优雅的办法，就是在自己项目文件中建一个和Spring源码相同的包名类名的文件并将新建的<code>AbstractDataBufferDecoder&lt;T&gt;</code>这个类的缓存区调大即可，最后采用了这种方案解决了问题。</p>
<p><img src="https://molzhao-pic.oss-cn-beijing.aliyuncs.com/2022/2022-02-16/Buffer.png" alt=""></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> org.springframework.core.codec;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.reactivestreams.Publisher;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.ResolvableType;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.io.buffer.DataBuffer;</span><br><span class="line"><span class="keyword">import</span> org.springframework.core.io.buffer.DataBufferUtils;</span><br><span class="line"><span class="keyword">import</span> org.springframework.lang.Nullable;</span><br><span class="line"><span class="keyword">import</span> org.springframework.util.MimeType;</span><br><span class="line"><span class="keyword">import</span> reactor.core.publisher.Flux;</span><br><span class="line"><span class="keyword">import</span> reactor.core.publisher.Mono;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Map;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Spring硬编码maxInMemorySize，未找到修改该值的方法，所以直接覆盖</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * Abstract base class for &#123;<span class="doctag">@code</span> Decoder&#125; implementations that can decode</span></span><br><span class="line"><span class="comment"> * a &#123;<span class="doctag">@code</span> DataBuffer&#125; directly to the target element type.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Sub-classes must implement &#123;<span class="doctag">@link</span> #decodeDataBuffer&#125; to provide a way to</span></span><br><span class="line"><span class="comment"> * transform a &#123;<span class="doctag">@code</span> DataBuffer&#125; to the target data type. The default</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> #decode&#125; implementation transforms each individual data buffer while</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> #decodeToMono&#125; applies "reduce" and transforms the aggregated buffer.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * &lt;p&gt;Sub-classes can override &#123;<span class="doctag">@link</span> #decode&#125; in order to split the input stream</span></span><br><span class="line"><span class="comment"> * along different boundaries (e.g. on new line characters for &#123;<span class="doctag">@code</span> String&#125;)</span></span><br><span class="line"><span class="comment"> * or always reduce to a single data buffer (e.g. &#123;<span class="doctag">@code</span> Resource&#125;).</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@author</span> Rossen Stoyanchev</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@since</span> 5.0</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param</span> &lt;T&gt; the element type</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@SuppressWarnings</span>(<span class="string">"deprecation"</span>)</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">AbstractDataBufferDecoder</span>&lt;<span class="title">T</span>&gt; <span class="keyword">extends</span> <span class="title">AbstractDecoder</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">	<span class="comment">// 原Spring中的该值为262144</span></span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> maxInMemorySize = <span class="number">10</span> * <span class="number">1024</span> * <span class="number">1024</span>;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="title">AbstractDataBufferDecoder</span><span class="params">(MimeType... supportedMimeTypes)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(supportedMimeTypes);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Configure a limit on the number of bytes that can be buffered whenever</span></span><br><span class="line"><span class="comment">     * the input stream needs to be aggregated. This can be a result of</span></span><br><span class="line"><span class="comment">     * decoding to a single &#123;<span class="doctag">@code</span> DataBuffer&#125;,</span></span><br><span class="line"><span class="comment">     * &#123;<span class="doctag">@link</span> java.nio.ByteBuffer ByteBuffer&#125;, &#123;<span class="doctag">@code</span> byte[]&#125;,</span></span><br><span class="line"><span class="comment">     * &#123;<span class="doctag">@link</span> org.springframework.core.io.Resource Resource&#125;, &#123;<span class="doctag">@code</span> String&#125;, etc.</span></span><br><span class="line"><span class="comment">     * It can also occur when splitting the input stream, e.g. delimited text,</span></span><br><span class="line"><span class="comment">     * in which case the limit applies to data buffered between delimiters.</span></span><br><span class="line"><span class="comment">     * &lt;p&gt;By default this is set to 256K.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> byteCount the max number of bytes to buffer, or -1 for unlimited</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@since</span> 5.1.11</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMaxInMemorySize</span><span class="params">(<span class="keyword">int</span> byteCount)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.maxInMemorySize = byteCount;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Return the &#123;<span class="doctag">@link</span> #setMaxInMemorySize configured&#125; byte count limit.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@since</span> 5.1.11</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">getMaxInMemorySize</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.maxInMemorySize;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Flux&lt;T&gt; <span class="title">decode</span><span class="params">(Publisher&lt;DataBuffer&gt; input, ResolvableType elementType,</span></span></span><br><span class="line"><span class="function"><span class="params">                          @Nullable MimeType mimeType, @Nullable Map&lt;String, Object&gt; hints)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> Flux.from(input).map(buffer -&gt; decodeDataBuffer(buffer, elementType, mimeType, hints));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Mono&lt;T&gt; <span class="title">decodeToMono</span><span class="params">(Publisher&lt;DataBuffer&gt; input, ResolvableType elementType,</span></span></span><br><span class="line"><span class="function"><span class="params">                                @Nullable MimeType mimeType, @Nullable Map&lt;String, Object&gt; hints)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> DataBufferUtils.join(input, <span class="keyword">this</span>.maxInMemorySize)</span><br><span class="line">                .map(buffer -&gt; decodeDataBuffer(buffer, elementType, mimeType, hints));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * How to decode a &#123;<span class="doctag">@code</span> DataBuffer&#125; to the target element type.</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@deprecated</span> as of 5.2, please implement</span></span><br><span class="line"><span class="comment">     * &#123;<span class="doctag">@link</span> #decode(DataBuffer, ResolvableType, MimeType, Map)&#125; instead</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="meta">@Deprecated</span></span><br><span class="line">    <span class="meta">@Nullable</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> T <span class="title">decodeDataBuffer</span><span class="params">(DataBuffer buffer, ResolvableType elementType,</span></span></span><br><span class="line"><span class="function"><span class="params">                                 @Nullable MimeType mimeType, @Nullable Map&lt;String, Object&gt; hints)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> decode(buffer, elementType, mimeType, hints);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="升级SpringBoot版本"><a href="#升级SpringBoot版本" class="headerlink" title="升级SpringBoot版本"></a>升级SpringBoot版本</h3><p>按照网上大量资料的说法在SpringBoot高版本中这个问题得到了解决，但是在一个稳定运行的线上项目，想要升级SpringBoot版本风险实在太大，因为有很多未知的坑。因此这种方法一开始就被摒弃了。有兴趣的可以自己尝试下高版本中是否开启这项配置有效。</p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Gateway/index.html" rel="tag"># Gateway</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/p/dd88d89c.html" rel="next" title="碳循环饮食法">
                <i class="fa fa-chevron-left"></i> 碳循环饮食法
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/p/f8011293.html" rel="prev" title="TCP连接数以NGINX是否启用长链接对照组实验">
                TCP连接数以NGINX是否启用长链接对照组实验 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="MolZhao" />
            
              <p class="site-author-name" itemprop="name">MolZhao</p>
              <p class="site-description motion-element" itemprop="description">沉淀</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/index.html">
              
                  <span class="site-state-item-count">54</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">30</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/normcorer" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:MolZhaovo@163.com" target="_blank" title="Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#系统配置及版本"><span class="nav-number">2.</span> <span class="nav-text">系统配置及版本</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#全局过滤器"><span class="nav-number">3.</span> <span class="nav-text">全局过滤器</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#统一接口权限"><span class="nav-number">4.</span> <span class="nav-text">统一接口权限</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#统一APIGateway-knife4j接入"><span class="nav-number">5.</span> <span class="nav-text">统一APIGateway knife4j接入</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#网关侧配置"><span class="nav-number">5.1.</span> <span class="nav-text">网关侧配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#业务服务侧配置"><span class="nav-number">5.2.</span> <span class="nav-text">业务服务侧配置</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#动态路由"><span class="nav-number">6.</span> <span class="nav-text">动态路由</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#跨域及重复跨域问题解决"><span class="nav-number">7.</span> <span class="nav-text">跨域及重复跨域问题解决</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#什么是跨域"><span class="nav-number">7.1.</span> <span class="nav-text">什么是跨域</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#重复跨域解决"><span class="nav-number">7.2.</span> <span class="nav-text">重复跨域解决</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Exceeded-limit-on-max-bytes-to-buffer-262144"><span class="nav-number">8.</span> <span class="nav-text">Exceeded limit on max bytes to buffer : 262144</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#配置文件配置缓冲区大小"><span class="nav-number">8.1.</span> <span class="nav-text">配置文件配置缓冲区大小</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#配置类配置缓冲区大小"><span class="nav-number">8.2.</span> <span class="nav-text">配置类配置缓冲区大小</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#重写Spring原文件"><span class="nav-number">8.3.</span> <span class="nav-text">重写Spring原文件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#升级SpringBoot版本"><span class="nav-number">8.4.</span> <span class="nav-text">升级SpringBoot版本</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2024</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MolZhao</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">ZYJ</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>






        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i> 访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i> 总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    
      <div id="needsharebutton-float">
        <span class="btn">
          <i class="fa fa-share-alt" aria-hidden="true"></i>
        </span>
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script type="text/javascript" src="/js/src/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: '18BuKzLQMbUp8ECwDBiHu6Df-MdYXbMMI',
        appKey: 'xVTsu5pYLayqSvClr36TzcAH',
        placeholder: '(•̀へ•╮)',
        avatar:'identicon',
        guest_info:guest,
        pageSize:'10' || 10,
    });

    $('.vpower').html('');
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "./public/search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
      flOptions = {};
      
          flOptions.iconStyle = "default";
      
          flOptions.boxForm = "horizontal";
      
          flOptions.position = "middleRight";
      
          flOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-float', flOptions);
    
  </script>

  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"scale":1,"hHeadPos":0.5,"vHeadPos":0.5,"jsonPath":"/live2dw/assets/assets/wanko.model.json"},"display":{"superSample":2,"width":150,"height":150,"position":"right","hOffset":30,"vOffset":20},"mobile":{"show":false,"scale":0.05},"react":{"opacityDefault":0.6,"opacityOnHover":0.2},"log":false});</script></body>
</html>
